//index.js
//获取应用实例
var app = getApp();
var constract = require('../../utils/constract.js');
var comm = require('../../utils/common.js');
//id(card id) uid(用户id) 
var uid,id;

function generateImg(token, certificState, cardId){
  wx.request({
    url: constract.generateImg,
    header: { token: token },
    data: { state: certificState, cardId: cardId },
    success: function (res) {
      console.log(res);
      if (wx.hideLoading) {
        wx.hideLoading();
      };
      var img = res.data.data.url;
      wx.previewImage({
        urls: [img]
      })
    },
    fail: function (err) {
      console.log(err)
    },
    complete: function () {
      if (wx.hideLoading) {
        wx.hideLoading();
      };
    }
  })
}

Page({
  data: {
    erm: true, 
    show: false,
    swiperIdx: 0,
    certificState: 1,
    getAuth: false,
    noAuth: false,
  },
  queryMultipleNodes: function(){
    var that = this;
    var aboutArr = [];
    wx.createSelectorQuery().selectAll('.site-about-info').boundingClientRect(function(rects){
      rects.forEach(function(rect){
        // console.log(rect.bottom);// 节点的下边界坐标
        aboutArr.push(rect.bottom);
      })
      // console.log(aboutArr);
      that.setData({
        aboutArr:aboutArr
      })
    }).exec();
  },
  onLoad: function (options) {
    var that = this;
    wx.hideShareMenu();

    app.Verification(function (token) {
      wx.request({
        url: constract.index, //查看首页的名片信息
        header: { token: token },
        success: function (res) {
          console.log(res);
          if(res.data.code === '13000'){
            wx.showModal({
              title: '提示',
              content: '加载失败,请稍后重试！',
              cancel: false,
              success: function (res) {
                if (res.confirm) {
                  
                }
              }
            })
            return;
          } else if(res.data.code === '23000') {
            that.setData({
              noAuth: true
            })
            wx.setStorageSync('noAuth',true);
            return;
          } else {
            that.setData({
              noAuth: false
            })
            wx.removeStorageSync('noAuth');
          }
          

          if (res.data.data.user.length > 0) {
            uid = res.data.data.user[0].uid;
            app.globalData.myCardId = res.data.data.user[0].id;//放在onShow里造成第二次分享变为第一个问题
            id = app.globalData.myCardId;
          }

        }
      });
    });

    //获取窗口高度
    wx.getSystemInfo({
      success: (res) => {
        wx.getSystemInfo({
          success: (res) => {
            // console.log(res.windowHeight);
            that.setData({
              swiperHeight: res.windowHeight,
            })
          }
        })
      }
    });
  },
  onShow: function () {
    var that = this;
    var swiperIdx = app.globalData.swiperIdx || 0;

    // console.log(swiperIdx);
    that.setData({
      swiperIdx: swiperIdx,
    })
    
    app.Verification(function (token) {
      wx.request({
        url: constract.index, //查看首页的名片信息
        header: { token: token },
        success: function (res) {
          console.log(res);
          if(res.data.code === '13000'){
            return;
          } else if(res.data.code === '23000') {
            that.setData({
              noAuth: true
            })
            return;
          } else {
            that.setData({
              noAuth: false
            })
            wx.removeStorageSync('noAuth');
          }

          var userInfo = res.data.data;
          
          if (res.data.data.user.length > 0){
            uid = res.data.data.user[0].uid;
            id = res.data.data.user[swiperIdx].id;
          }
          
          if (userInfo.state == 0) { //state 判断是否添加名片
            that.setData({
              promptShow: true, //判断是否授权
            })
            
            wx.request({
              url: constract.defaultName, //查看首页的名片信息
              header: { token: token },
              success: function (res) {
                console.log(res);
                app.globalData.nickName = res.data.name;
                app.globalData.avatarUrl = res.data.avatar;

                userInfo.name = app.globalData.nickName;
                userInfo.avatar = app.globalData.avatarUrl;

                that.setData({
                  userInfo: userInfo
                });

              }
            })
          
          } else {
            that.setData({
              userInfo: userInfo,
              certificState: res.data.data.certificState || ''
            });
            
            setTimeout(function(){
              that.queryMultipleNodes();
            },100);
          }
        }
      });
    });
    
  },
  share: function () {
    if (!wx.canIUse('button.open-type.share')) {
      wx.showModal({
        title: '提示',
        content: '点击右上角转发分享',
        showCancel: false
      });
    }
  },
  know: function () {
    this.setData({
      show: false
    })
  },
  generate: function (e) {
    var certificState = e.currentTarget.dataset.generate;
    var cardId = e.currentTarget.dataset.cardid;
    var qrCode = e.currentTarget.dataset.code;

    if (certificState == null) {
      certificState = 0;
    }
    if (wx.showLoading) {
      wx.showLoading({
        title: '生成中',
        mask: true,
      });
    }
    app.Verification(function (token) {
      if (qrCode === '' || qrCode === undefined){
        wx.request({
          url: constract.changeCode,
          header: { token: token },
          data: { cardId: cardId },
          success: (res) => {
            // console.log(res);
            if(+res.data.code === 12000) {
              generateImg(token, certificState, cardId);
            }
          }
        })
      } else {
        generateImg(token,certificState, cardId);
      }

    })
  },

  //swiper滑动获取当前名片id作为分享
  swiperChange: function(e){
    var idx = e.detail.current;
    id = this.data.userInfo.user[idx].id;
    app.globalData.swiperIdx = idx;
  },

  onShareAppMessage: function (res) { //这里id受编辑影响
    if (res.target && res.target.dataset.cardid) {
      id = res.target.dataset.cardid;
    }

    return {
      title: '幸会！这是我名片请惠存！',
      path: '/pages/partner/partner?id=' + id + '&uid=' + uid
    }
  },

  promptCancel: function(){//取消
    this.setData({
      promptShow: false
    })
  },
  hideAuth: function(){
    this.setData({
      getAuth: false
    })
  },
  onGotUserInfo: function(e){//允许
    if(e.detail.errMsg === "getUserInfo:fail auth deny") {
      this.setData({
        getAuth: true
      })
    } else {
      wx.removeStorageSync('noAuth');
      wx.navigateTo({
        url: `/pages/add-card/add-card?avatar=${e.detail.userInfo.avatarUrl}&name=${e.detail.userInfo.nickName}`
      })
    }
  }

})
